import "@ethersproject/shims";
import { ethers } from 'ethers';
import moment from 'moment';
import { global } from "@/config/config";
import api from '@/request/api'
import { max } from '@/utils/util'
import { getValue } from "../deviceStorage";

let rpcProvider
let rpcNode = getValue('RPCNode')
if (rpcNode && rpcNode.includes('http')) {
    rpcProvider = new ethers.providers.JsonRpcProvider(rpcNode);
} else {
    rpcProvider = new ethers.providers.JsonRpcProvider(global.RPCNode);
}
const httpsProvider = rpcProvider

// 调用RPC curl -H 'Content-type: application/json' "https://goerli.infura.io/v3/ed0f0f32356245dabbdc84fa43b643e1" -d '{"jsonrpc":"2.0", "method":" eth_getBalance", "params":[], "id":1}'
export const getETHBalance = async (owner) => {
    const balance = await httpsProvider.getBalance(owner);
    //余额是 BigNumber (in wei); 格式化为 ether 字符串
    let etherString = ethers.utils.formatEther(balance)
    return etherString;
}

export const getTransactionDetail = async (txHash) => {
    let result = await httpsProvider.getTransaction(txHash)
    let obj = await httpsProvider.getTransactionReceipt(txHash)
    result.gasUsed = obj.gasUsed
    return result
}

export const transferETH = async (mnemonicStr, tx) => {
    let selectedWallet = getValue('selectedWallet')
    const wallet = ethers.Wallet.fromMnemonic(mnemonicStr, selectedWallet.wallet_name)
    // 签署交易.
    const signedTx = await wallet.signTransaction(tx);
    //交易hash
    const txHash = ethers.utils.keccak256(signedTx);
    console.log("txHash", txHash)
    //发送交易.
    const result = await api.eth_transfer(signedTx);
    if (txHash === result.result) {
        return true
    } else {
        false
    }
}

export const getETHGasData = async (rpcurl, fromAddress, toAddress, amount) => {
    //获取矿工费
    let nonce, maxpriorityfee, maxpriorityfeestatic, blocknumber, base_fee, gaslimit
    await api.eth_getTransactionCount(rpcurl, fromAddress).then(res => {
        nonce = parseInt(res.result)
    })
    await api.get_maxPriorityFeePerGas(rpcurl).then(res => {
        let re = parseInt(res.result) / Math.pow(10, 9)
        maxpriorityfee = re
        maxpriorityfeestatic = re
    })
    await api.get_blockinfo(rpcurl).then(res => {
        blocknumber = res.result
    })
    await api.get_newblockinfo(rpcurl, blocknumber).then(res => {
        base_fee = parseInt(res.result.baseFeePerGas) / 1000000000
        base_fee = new Number(base_fee)
    })
    let maxfee = (maxpriorityfee * Math.pow(10, 9) + base_fee * Math.pow(10, 9)) / Math.pow(10, 9)
    let maxfeestatic = (maxpriorityfee * Math.pow(10, 9) + base_fee * Math.pow(10, 9)) / Math.pow(10, 9)
    let gasprice = max(maxfee, maxpriorityfee)
    // if (coinType == 'BSC') {
    //     await api.get_price(rpcurl).then(res => {
    //         gasprice = parseInt(res.result) / Math.pow(10, 9)
    //     })
    // }
    let money = parseFloat(amount) * Math.pow(10, 18)
    let inputdata = "0x"
    await api.get_limit(rpcurl, fromAddress, toAddress, inputdata).then(res => {
        gaslimit = parseInt(res.result)
    })
    let gas = gaslimit * gasprice
    gas = gas / Math.pow(10, 9)
    let obj = {
        nonce,
        maxpriorityfee,
        maxpriorityfeestatic,
        blocknumber,
        base_fee,
        maxfee,
        maxfeestatic,
        gasprice,
        gaslimit,
        gas,
        value: "0x" + money.toString(16)
    }
    return obj
}

export const getETHTxData = (gasData, toAddress) => {
    let tx = {
        type: 2,
        nonce: gasData.nonce,
        to: toAddress,
        maxPriorityFeePerGas: "0x" + (gasData.maxpriorityfee * Math.pow(10, 9)).toFixed().toString(16),
        maxFeePerGas: "0x" + (gasData.maxfee * Math.pow(10, 9)).toFixed().toString(16),
        gasLimit: "0x" + gasData.gaslimit.toString(16),
        value: gasData.value,
        chainId: 5
    }
    return tx
}

export const getETHTransferHistory = async (payload) => {
    let url = global.BaseURL + "waddr_tran/"
    let startTime = moment(payload.create_time).format("X")
    let endTime = moment().format("X")
    let result = await api.get_transferHistory(url, payload.address, startTime, endTime, 20)
    let sendCount = 0
    let receiveCount = 0
    result && result.forEach(item => {
        if (item.from_address.toLowerCase() === payload.address.toLowerCase()) {
            item.type = 'send'
            sendCount++
        } else {
            item.type = 'receive'
            receiveCount++
        }
        item.valueLabel = ethers.utils.formatEther(item.value) + ' ETH'
    })
    let obj = {
        list: result,
        showReceive: receiveCount > 0 ? true : false,
        showSend: sendCount > 0 ? true : false
    }
    return obj
}

export const getETHTransferDetail = async (obj) => {
    let url = global.BaseURL + "waddr_tran/"
    let startTime = moment(obj.create_time).format("X")
    let endTime = moment().format("X")
    let result = await api.get_transferHistory(url, obj.address, startTime, endTime, 20)
    result && result.forEach(item => {
        if (item.from_address.toLowerCase() === obj.address.toLowerCase()) {
            item.type = 'send'
        } else {
            item.type = 'receive'
        }
    })
    return result
}